import Vue from "vue";

import VueRouter from "vue-router";

import store from "@/store"


//路由懒加载
const Register = () => import("@pages/Register")
const Login = () => import("@pages/Login")
const Home = () => import("@pages/Home")
const Search = () => import("@pages/Search")
const Detail = () => import("@pages/Detail");
const AddCartSuccess = () => import("@pages/AddCartSuccess");
const ShopCart = () => import("@pages/ShopCart");
const Trade = () => import("@pages/Trade");
const Pay = () => import("@pages/Pay");
const PaySuccess = () => import("@pages/PaySuccess");
const Center = () => import("@pages/Center");
const mayOrder = () => import("@pages/Center/mayOrder");
const temaOrder = () => import("@pages/Center/temaOrder");

Vue.use(VueRouter)

//重写push
//1.拿到原push方法
const lsatPush = VueRouter.prototype.push
VueRouter.prototype.push = function (location, onComplete = () => {}, onAbort = () => {}) {
    return lsatPush.call(this, location, onComplete, onAbort)
}


const router =  new VueRouter({
    scrollBehavior () {
        // return 期望滚动到哪个的位置
        return{
            x: 0,
            y: 0
        }
    },
    //history模式路由
    mode: "history",
    routes: [{
            path: "/register",
            component: Register,
            name: "register",
            //路由元信息
            meta: {isFooterHidden: true}
        },
        {
            path: "/login",
            component: Login,
            name: "login",
            //路由元信息
            meta: {isFooterHidden: true},
            //路由独享守卫限制登录状态不能在进登录路由
            /* beforeEnter(to , from , next){
                if(store.state.user.token){
                    next("/")
                }else{
                    next()
                }
            } */
        },
        {
            path: "/home",
            component: Home,
            name: "home"
        },
        {
            path: "/search/:keyword?",
            component: Search,
            name: "search"
        },
        {
            path: "/detail/:skuId",
            component: Detail,
            name: "detail",
        },
        {
            path: "/addCartSuccess",
            component: AddCartSuccess,
            name: "addCartSuccess",
            //路由独享守卫限制只能从添加购物车成功进入这个路由
            beforeEnter(to , from , next){
                if(sessionStorage.getItem("cartData")){
                    next()
                }else{
                    next("/shopCart")
                }
            }
        },
        {
            path: "/shopCart",
            component: ShopCart,
            name: "shopCart",
        },
        {
            path: "/",
            redirect: "/home"
        },
        {
            path: "/trade",
            component: Trade,
            name: "trade",
            //添加路由独享守卫,限制结算页面只能从购物车页面进入
            beforeEnter: (to, from, next) => {
                if(from.path === "/shopCart"){
                    next()
                }else{
                    next("/shopCart")
                }
            }
          },
          {
            path: "/pay",
            component: Pay,
            name: "pay",
            //添加路由独享守卫,限制支付页面只能从结算页面进入
            beforeEnter: (to, from, next) => {
                if(from.path === "/trade"){
                    next()
                }else{
                    next("/shopCart")
                }
            }
          },
          {
            path: "/paysuccess",
            component: PaySuccess,
            name: "paysuccess",
            //添加路由独享守卫,限制支付成功页面只能从支付页面进入
            beforeEnter: (to, from, next) => {
                if(from.path === "/pay"){
                    next()
                }else{
                    next("/shopCart")
                }
            }
          },
          {
            path: "/center",
            component: Center,
            name: "center",
            children:[
                {path: "/mayorder" , component: mayOrder , name: "mayorder"},
                {path: "/teamorder" , component: temaOrder , name: "temaorder"},
                {path: "/center" , component:mayOrder }
            ]
          },
        
    ]
})

router.beforeEach( async (to , from , next) => {
    //token校验逻辑:(目的:判断是否登录,并且登录后想要用户名)

     //使用一个数组,保存所有必须有token才能访问的路由地址
     const checkPath = ["/center", "/pay", "/paysuccess", "/trade"]

     //判断当前要去的地址是否需要token校验
     const isCheckPath = checkPath.some((item) => {
        return to.path.startsWith(item)
     })


     //拿到token,和用户名
     const token = store.state.user.token
     const nickName = store.state.user.nickName

     //如果有用户名就直接放行
     if(nickName){
        return next()
     }

     //如果没有用户名则判断需不需要权限校验
     if(isCheckPath){
        if(token){
            //有token放行,并获取用户名，token有可能失效，dispatch方法返回promise实例
            try {
                await store.dispatch("user/getUserInfo")
                next()
            } catch (error) {
                next("/login")
            }
        }else{
            //没有token则去登录页面
            next("/login")
        }

     }else{
        //不需要权限校验的页面如果有token则顺便获一下用户名
        if(token){
            console.log(store.dispatch("user/getUserInfo") , "dispatch返回值");
            try {
                await store.dispatch("user/getUserInfo")
                console.log("请求用户名成功okkk , 去home页面");
                next()
            } catch (error) {
                console.log("请求用户名失败回到login页面");
                next("/login")
            }
        }
        //不需要权限校验的页面如果没有token则不管直接放行
        next()
     }


})


export default router